package com.huatai.model.controller;

import com.huatai.common.api.R;
import com.huatai.model.dto.FileInfoDTO;
import com.huatai.model.dto.UploadPartDTO;
import com.huatai.model.service.FileService;
import com.huatai.model.vo.FileUploadTaskVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 *
 * @author xuzy
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
public class FileController {

    @Autowired
	FileService fileService;

	@ApiOperation(value = "普通上传" , notes = "普通文件上传，上传文件成功返回文件路径")
	@PostMapping("/upload")
	public R<String> upload(MultipartFile file){
		return R.data(fileService.upload(file));
	}

	@ApiOperation(value = "文件下载",notes = "文件路径")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "url",value = "文件路径",required = true,dataType = "String"),
		@ApiImplicitParam(name = "partIndex",value = "分片索引，按分片索引下载时必填",dataType = "Integer"),
		@ApiImplicitParam(name = "offset",value = "偏移量，按偏移量下载时需要",dataType = "Long"),
		@ApiImplicitParam(name = "length",value = "长度，按偏移量下载时需要",dataType = "Long")
	})
	@RequestMapping(value = "/download",method = {RequestMethod.GET,RequestMethod.POST})
	public void fileDownload(@RequestParam("url") String url,@RequestParam("partIndex") Integer partIndex,@RequestParam("offset") Long offset,@RequestParam("length") Long length){
		if(null != partIndex){//分片按分片索引下载
			fileService.download(url,partIndex);
		}else{
			fileService.download(url,offset,length);
		}
	}

    @ApiOperation(value = "创建分片上传",notes = "创建分片上传任务")
    @PostMapping("/create/uploadTask")
    public R<FileUploadTaskVO> createUploadTask(@Valid @RequestBody FileInfoDTO dto){
        return R.data(fileService.createUploadTask(dto));
    }

    @ApiOperation("上传分片")
    @PostMapping("/upload/part")
    public R uploadPart(UploadPartDTO dto){
		fileService.uploadPart(dto);
        return R.data(null);
    }

    @ApiOperation("合并分片")
    @PostMapping("/complete/part")
    public R<String> completePart(@RequestBody FileInfoDTO dto){
        return R.data(fileService.completePart(dto));
    }

	@ApiOperation("取消上传任务")
	@GetMapping("/cancel/task/{md}")
	public R cancelTask(@PathVariable("md") String md){
		fileService.cancalTask(md);
		return R.success("操作成功");
	}

	@ApiOperation(value = "获取文件大小或分片数",notes = "大小单位字节byte")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "url",value = "路径",dataType = "String",required = true),
		@ApiImplicitParam(name = "type",value = "类型，大小：SIZE 分片数：PARTNUM",dataType = "String",required = true)
	})
	@GetMapping(value = "/fileSizeOrPartNumbers")
	public R<Long> fileSizeOrPartNumbers(@RequestParam("url") String url,@RequestParam("type") String type){
		return R.data(fileService.fileSizeOrPartNumbers(url,type));
	}

}
